package va_file;

import global.RID;
import heap.HFBufMgrException;
import heap.HFDiskMgrException;
import heap.HFException;
import heap.Heapfile;
import heap.InvalidSlotNumberException;
import heap.InvalidTupleSizeException;
import heap.SpaceNotAvailableException;
import heap.Tuple;

import java.io.IOException;

import va.Range;
import va.VAEntry;

public class VAFile extends Heapfile {
	
	public static int BITS_PER_DIMENSTION = 4;
	public static final int DEFAULT_BITS = 4;
	public static int RANGE_UPPER_BOUND = 10000;
	public static int RANGE_LOWER_BOUND = -10000;
	
	public VAFile(String name) throws HFException, HFBufMgrException,
			HFDiskMgrException, IOException {
		super(name);
	}
	
	// Returns the default ranges to calculate the VA approximations
	
	public static Range[] GetDefaultRanges() {
		return Range.DefineRanges(BITS_PER_DIMENSTION, RANGE_LOWER_BOUND, RANGE_UPPER_BOUND);
	}
	
	/*
	 * Returns the default ranges to calculate the VA approximations
	 * Mark Yates - need to be able to pass in bits per dimension for project 3
	 */
	public static Range[] GetDefaultRanges(int bitsPerDim) {
		return Range.DefineRanges(bitsPerDim, RANGE_LOWER_BOUND, RANGE_UPPER_BOUND);
	}
	
	// Inserts a record into the VAFile
	
	public RID insertRecord(VAEntry entry) throws IOException, InvalidSlotNumberException, InvalidTupleSizeException, SpaceNotAvailableException, HFException, HFBufMgrException, HFDiskMgrException {
		byte[] bytes = entry.toBytes();
		RID rid=super.insertRecord(bytes);
		return rid;
	}

    // Deletes a VA entry from the index file

    public void deleteEntry(VAEntry entry) throws Exception {
        VAFileScan scanner = this.openVAScan();
        VAEntry currentEntry = scanner.getNextHeapVA();
        while (currentEntry != null) {
            if (entry.rid.equals(currentEntry.rid)) {
                this.deleteRecord(scanner.fileScan.currentRID);
            }
            currentEntry = scanner.getNextHeapVA();
        }
        scanner.close();
    }
	
	// Gets an approximation from the VAFile
	
	public VAEntry getVARecord(RID rid) throws InvalidSlotNumberException, InvalidTupleSizeException, HFException, HFDiskMgrException, HFBufMgrException, Exception {
		Tuple tuple = super.getRecord(rid);
	    byte[] bytes = tuple.getTupleByteArray();
	    return VAEntry.fromBytes(bytes);
	}
	
	// Retrieves a special VAFileScan object to scan the elements of the VAFile
	
	public VAFileScan openVAScan() throws InvalidTupleSizeException, IOException {
		return new VAFileScan(this);
	}

}
